package com.zenithmind.gateway.auth;

import com.zenithmind.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 默认Token提取器实现
 * 专门负责从HTTP请求中提取JWT token
 * 遵循单一职责原则：只负责token的提取逻辑
 */
@Slf4j
@Component
public class DefaultTokenExtractor implements TokenExtractor {

    @Override
    public String extractToken(ServerHttpRequest request) {
        log.trace("开始提取token");
        
        // 首先尝试从token头获取
        String token = request.getHeaders().getFirst("token");
        
        // 如果没有，尝试从Authorization头获取
        if (StringUtils.isBlank(token)) {
            String authHeader = request.getHeaders().getFirst("Authorization");
            if (StringUtils.isNotBlank(authHeader)) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7);
                } else if (authHeader.startsWith(CommonConstants.TOKEN_PREFIX)) {
                    token = authHeader.replace(CommonConstants.TOKEN_PREFIX, "");
                }
            }
        } else if (token.startsWith(CommonConstants.TOKEN_PREFIX)) {
            token = token.replace(CommonConstants.TOKEN_PREFIX, "");
        }
        
        if (StringUtils.isNotBlank(token)) {
            log.trace("成功提取到token");
        } else {
            log.trace("未找到token");
        }
        
        return token;
    }
}
